import { Controller, Context, Get, Post, Use, sfn } from "nb2";
import jwt from "jsonwebtoken";
import { generateRandom } from "../common/utils.js";
import { prisma } from "../prisma.js";
import { ResBody, Token } from "../common/model.js";
import { handleAuth } from "../common/handleAuth.js";

@Controller("user")
export class User {
  @Use(handleAuth)
  @Post("info")
  async [sfn()](ctx: Context) {
    const token = ctx.custom.token as Token;
    const body = await ctx.body("json");
    const user = await prisma.user.update({
      where: { id: token.uid },
      data: { nickname: body.nickname, intro: body.intro, avatar: body.avatar },
    });
    ctx.json<ResBody>({ code: 200, user, msg: "更新成功" });
  }

  @Get("/info")
  async [sfn()](ctx: Context) {
    const { account } = ctx.query;
    const select = {
      id: true,
      intro: true,
      nickname: true,
      avatar: true,
      account: true,
    };
    if (account) {
      const user = await prisma.user.findUnique({
        where: { account },
        select,
      });

      return ctx.json<ResBody>({ code: 200, user });
    }

    handleAuth(ctx, async () => {
      const token = ctx.custom.token as Token;
      const user = await prisma.user.findUnique({
        where: { id: token.uid },
        select,
      });
      ctx.json<ResBody>({ code: 200, user });
    });
  }

  @Post("created")
  async [sfn()](ctx: Context) {
    const body = await ctx.body("json");

    const user = await prisma.user.findUnique({
      where: { phone: body.phone },
    });

    if (user) {
      return ctx.json<ResBody>({ code: 400, msg: "该账号已注册" });
    }

    // 生成account
    const account = generateRandom(6);
    // 默认昵称 = user[account]
    const nickname = `user_${account}`;

    const userd = await prisma.user.create({
      data: {
        nickname,
        phone: body.phone,
        account: account.toString(),
        password: body.password,
      },
    });
    ctx.json<ResBody>({ code: 200, msg: "注册成功", user: userd });
  }

  @Post("login")
  async qweqw(ctx: Context) {
    const body = await ctx.body("json");

    const user = await prisma.user.findUnique({
      where: { phone: body.phone },
    });

    if (!user) {
      return ctx.json<ResBody>({ code: 400, msg: "账号不存在" });
    }

    if (user.password !== body.password) {
      return ctx.json<ResBody>({ code: 400, msg: "密码错误" });
    }

    //签发token
    const token = jwt.sign(
      {
        uid: user.id,
        name: user.nickname,
        account: user.account,
      },
      process.env.JWT_KEY!,
      { expiresIn: process.env.JWT_EXP }
    );
    ctx.json<ResBody>({ code: 200, msg: "登录成功", token, user });
  }
}
